package com.eqdd.yiqidian.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.net.Uri;
import android.os.Handler;
import android.support.multidex.MultiDex;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.bulong.rudeness.RudenessScreenHelper;
import com.eqdd.library.percentUtil.WindowUtil;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.bean.BaseBean;
import com.eqdd.yiqidian.bean.rebuild.GroupListResultBean;
import com.eqdd.yiqidian.bean.rebuild.GroupMemberListResultBean;
import com.eqdd.yiqidian.helper.mvchelper.LoadViewFractory;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpPresneter;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.http.JsonCallBack;
import com.eqdd.yiqidian.http.JsonConverter;
import com.eqdd.yiqidian.listener.rongyun.ConnectionStatusListener;
import com.eqdd.yiqidian.listener.rongyun.ConversationBehaviorListener;
import com.eqdd.yiqidian.listener.rongyun.ReceiveMessageListener;
import com.eqdd.yiqidian.rongyun.message.link.LinkMessage;
import com.eqdd.yiqidian.rongyun.message.link.LinkMessageItemProvider;
import com.eqdd.yiqidian.rongyun.message.mingpian.MingpianMessage;
import com.eqdd.yiqidian.rongyun.message.mingpian.MingpianMessageItemProvider;
import com.eqdd.yiqidian.rongyun.plugin.MyExtensionModel;
import com.eqdd.yiqidian.ui.MainActivity;
import com.eqdd.yiqidian.utils.EncryptUtil;
import com.eqdd.yiqidian.utils.GreenDaoUtil;
import com.eqdd.yiqidian.utils.GsonUtils;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.facebook.stetho.Stetho;
import com.facebook.stetho.okhttp3.StethoInterceptor;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.cookie.CookieJarImpl;
import com.lzy.okgo.cookie.store.SPCookieStore;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;
import com.lzy.okgo.model.Response;
import com.lzy.okrx2.adapter.FlowableBody;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.Logger;
import com.shizhefei.mvc.MVCHelper;
import com.squareup.leakcanary.LeakCanary;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.youku.cloud.player.YoukuPlayerConfig;
import com.zxy.tiny.Tiny;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;

import cafe.adriel.androidaudioconverter.AndroidAudioConverter;
import cafe.adriel.androidaudioconverter.callback.ILoadCallback;
import cn.jiguang.share.android.api.JShareInterface;
import cn.jpush.android.api.JPushInterface;
import cn.smssdk.SMSSDK;
import io.reactivex.Flowable;
import io.reactivex.Scheduler;
import io.reactivex.schedulers.Schedulers;
import io.rong.callkit.RongCallKit;
import io.rong.imkit.DefaultExtensionModule;
import io.rong.imkit.IExtensionModule;
import io.rong.imkit.RongExtensionManager;
import io.rong.imkit.RongIM;
import io.rong.imkit.userInfoCache.RongUserInfoManager;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Group;
import io.rong.imlib.model.UserInfo;
import me.leolin.shortcutbadger.ShortcutBadger;
import okhttp3.OkHttpClient;
import shortbread.Shortbread;


/**
 * Created by vzhihao on 2016/11/1.
 */
public class BaseApplication extends Application {
    //运用list来保存们每一个activity是关键
    private List<Activity> mList = new LinkedList();
    //为了实现每次使用该类时不创建新的对象而创建的静态对象
    private static BaseApplication application;
    //应用程序启动就调用，代表整个应用
    public static Handler handler;

    public static Context context;

    public static int mainTid;
    // 填写从短信SDK应用后台注册得到的APPKEY
    private static String APPKEY = "1b8496b059b30";
    private static String APPSECRET = "daa0b3099e8bfd736af50955e79da286";
    private static String BUGLY_APPID = "56663f923a";
    //请在这里输入你的应用的clientId，clientSecret
    public static final String CLIENT_ID_WITH_AD = "e29c9b1e28715061";
    public static final String CLIENT_SECRET_WITH_AD = "ae0a02d59900d2df6fcdd53454d66940";

    @Override
    public void onCreate() {
        super.onCreate();
//        String certificateSHA1Fingerprint = EncryptUtil.getCertificateSHA1Fingerprint(this);
//        System.out.println(certificateSHA1Fingerprint);
//        LeakCanary.install(this);
        context = application = this;
        handler = new Handler();
        mainTid = android.os.Process.myTid();
        initThirdService();
        initRongService();
        //#################不可放在子线程执行的初始化#################
        ToastMar.builder.init(getApplicationContext());
        SMSSDK.initSDK(this, APPKEY, APPSECRET, false);
        //#################不可放在子线程执行的初始化#################
        registerActivityLifecycleCallbacks(new BaseActivityLifeCallBack());
    }

    private void initRongService() {
        initRongIm();
        RongIM.setConnectionStatusListener(new ConnectionStatusListener());
        RongIM.setConversationBehaviorListener(new ConversationBehaviorListener());
        RongIM.setOnReceiveMessageListener(new ReceiveMessageListener());
        Conversation.ConversationType[] types = new Conversation.ConversationType[]{
                Conversation.ConversationType.PRIVATE,
                Conversation.ConversationType.GROUP
        };
        RongIM.getInstance().setReadReceiptConversationTypeList(types);
        RongIM.setGroupInfoProvider(s -> {
            System.out.println("融云服务器来获取group数据了" + s);
            GroupListResultBean groupById = GreenDaoUtil.getGroupById(s);
            if (groupById == null) {
                return null;
            } else {
                return new Group(groupById.getGroupid(), groupById.getGroupname(), Uri.parse(groupById.getGroupphoto()));
            }
        }, true);
        RongCallKit.setGroupMemberProvider((groupId, result) -> {
            OkGo.<HttpResult<List<GroupMemberListResultBean>>>post(HttpConfig.BASE_URL + HttpConfig.GROUP_USER_LIST)
                    .params("groupid", groupId)
                    .converter(new JsonConverter<HttpResult<List<GroupMemberListResultBean>>>() {
                        @Override
                        public void test() {
                            super.test();
                        }
                    })
                    .adapt(new FlowableBody<>())
                    .flatMap(listHttpResult -> Flowable.fromIterable(listHttpResult.getItems()))
                    .map(friendBean -> {
                        UserInfo userInfo = new UserInfo(friendBean.getGuid(), friendBean.getUpname(), Uri.parse(friendBean.getIphoto()));
                        RongIM.getInstance().refreshUserInfoCache(userInfo);
                        return userInfo.getUserId();
                    })
                    .toList()
                    .subscribe(userInfos -> result.onGotMemberList((ArrayList<String>) userInfos));
            return null;
        });
        RongIM.getInstance().setGroupMembersProvider((groupId, result) -> {
            OkGo.<HttpResult<List<GroupMemberListResultBean>>>post(HttpConfig.BASE_URL + HttpConfig.GROUP_USER_LIST)
                    .params("groupid", groupId)
                    .converter(new JsonConverter<HttpResult<List<GroupMemberListResultBean>>>() {
                        @Override
                        public void test() {
                            super.test();
                        }
                    })
                    .adapt(new FlowableBody<>())
                    .flatMap(listHttpResult -> Flowable.fromIterable(listHttpResult.getItems()))
                    .map(friendBean -> {
                        UserInfo userInfo = new UserInfo(friendBean.getGuid(), friendBean.getUpname(), Uri.parse(friendBean.getIphoto()));
                        RongIM.getInstance().refreshUserInfoCache(userInfo);
                        RongUserInfoManager.getInstance().setUserInfo(userInfo);
                        return userInfo;
                    })
                    .toList()
                    .subscribe(result::onGetGroupMembersResult);
        });
        List<IExtensionModule> extensionModules = RongExtensionManager.getInstance().getExtensionModules();
        IExtensionModule defaultExtensionModule = null;
        if (extensionModules != null) {
            for (IExtensionModule extensionModule : extensionModules) {
                if (extensionModule instanceof DefaultExtensionModule) {
                    defaultExtensionModule = extensionModule;
                    break;
                }
            }
            if (defaultExtensionModule != null) {
                RongExtensionManager.getInstance().unregisterExtensionModule(defaultExtensionModule);
            }
            RongExtensionManager.getInstance().registerExtensionModule(new MyExtensionModel());
        }
        RongIM.registerMessageType(MingpianMessage.class);
        RongIM.registerMessageTemplate(new MingpianMessageItemProvider());
        RongIM.registerMessageType(LinkMessage.class);
        RongIM.registerMessageTemplate(new LinkMessageItemProvider());
    }

    /**
     * 开线程初始化第三方,避免应用启动慢
     */
    private void initThirdService() {

        Schedulers.newThread().scheduleDirect(() -> {
            Shortbread.create(this);
            AndroidAudioConverter.load(this, new ILoadCallback() {
                @Override
                public void onSuccess() {
                    // Great!
                    System.out.println("great");
                }

                @Override
                public void onFailure(Exception error) {
                    System.out.println(error);
                    System.out.println("FFmpeg is not supported by device");
                }
            });
            WindowUtil.init(this);
            new RudenessScreenHelper(this, 630).activate();
            Tiny.getInstance().init(this);
//        ZXingLibrary.initDisplayOpinion(this);


        /*#######################极光推送######################*/

            JPushInterface.setDebugMode(true);
            JPushInterface.init(this);
//            JPushInterface.stopCrashHandler(this);
            JShareInterface.setDebugMode(true);
            JShareInterface.init(this);

        /*#######################极光推送######################*/


            Stetho.initializeWithDefaults(this);
            ShortcutBadger.applyCount(context, 7);
        /*#######################BUGLY######################*/

            /**
             * 只允许在MainActivity上显示更新弹窗，其他activity上不显示弹窗;
             * 不设置会默认所有activity都可以显示弹窗;
             */
            Beta.canShowUpgradeActs.add(MainActivity.class);
            Bugly.init(getApplicationContext(), BUGLY_APPID, false);
        /*#######################BUGLY######################*/
            initOkgoHttp(this);
//            YoukuPlayerConfig.setLog(true);
//            /**设置client_id和client_secret*/
//            YoukuPlayerConfig.setClientIdAndSecret(CLIENT_ID_WITH_AD,CLIENT_SECRET_WITH_AD);
//            /**sdk初始化*/
//            try {
//                YoukuPlayerConfig.onInitial(BaseApplication.this);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
            Logger.addLogAdapter(new AndroidLogAdapter());
//            MVCHelper.setLoadViewFractory(new LoadViewFractory());

        });
    }

    private void initOkgoHttp(Context context) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
        loggingInterceptor.setColorLevel(Level.INFO);
        builder.addNetworkInterceptor(new StethoInterceptor());
        builder.addInterceptor(loggingInterceptor);
        builder.cookieJar(new CookieJarImpl(new SPCookieStore(context)));
//---------这里给出的是示例代码,告诉你可以这么传,实际使用的时候,根据需要传,不需要就不传-------------//
//        HttpHeaders headers = new HttpHeaders();
//        headers.put("commonHeaderKey1", "commonHeaderValue1");    //header不支持中文，不允许有特殊字符
//        headers.put("commonHeaderKey2", "commonHeaderValue2");
//        HttpParams params = new HttpParams();
//        params.put("commonParamsKey1", "commonParamsValue1");     //param支持中文,直接传,不要自己编码
//        params.put("commonParamsKey2", "这里支持中文参数");
//-------------------------------------------------------------------------------------//

        OkGo.getInstance().init(this)                       //必须调用初始化
                .setOkHttpClient(builder.build())               //必须设置OkHttpClient
                .setCacheMode(CacheMode.NO_CACHE)               //全局统一缓存模式，默认不使用缓存，可以不传
                .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)   //全局统一缓存时间，默认永不过期，可以不传
                .setRetryCount(3);
        //全局统一超时重连次数，默认为三次，那么最差的情况会请求4次(一次原始请求，三次重连请求)，不需要可以设置为0
//                .addCommonHeaders(headers)                      //全局公共头
//                .addCommonParams(params);
    }

    private void initRongIm() {
        /**
         *
         * OnCreate 会被多个进程重入，这段保护代码，确保只有您需要使用 RongIM 的进程和 Push 进程执行了 init。
         * io.rong.push 为融云 push 进程名称，不可修改。
         */
        if (getApplicationInfo().packageName.equals(getCurProcessName(getApplicationContext()))) {

            /**
             * IMKit SDK调用第一步 初始化
             */
            RongIM.init(this);
            RongIMClient.init(this);

            if (getApplicationInfo().packageName.equals(getCurProcessName(getApplicationContext()))) {

                DemoContext.init(this);
            }
        }
    }

    /**
     * 获得当前进程的名字
     *
     * @param context
     * @return
     */
    @SuppressLint("NewApi")
    public static String getCurProcessName(Context context) {

        int pid = android.os.Process.myPid();

        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);

        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager
                .getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    public static Handler getHandler() {
        return handler;
    }

    public static Context getContext() {
        return context;
    }

    public synchronized static BaseApplication getApplication() {
        return application;
    }

    public List<Activity> getActivities() {
        return mList;
    }

    //杀进程
    public void onLowMemory() {
        super.onLowMemory();
        System.gc();
    }

    //定义枚举
    public enum ToastMar {
        builder;
        private View view;
        private TextView tv;
        private Toast toast;


        /**
         * 初始化Toast
         *
         * @param context
         */

        public void init(Context context) {
            view = LayoutInflater.from(context).inflate(R.layout.toast_view, null);
            tv = view.findViewById(R.id.toast_textview);
            toast = new Toast(context);
            toast.setView(view);
        }

        /**
         * 显示Toast
         *
         * @param content
         * @param duration Toast持续时间
         */
        public void display(CharSequence content, int duration) {
            if (content.length() != 0) {
                tv.setText(content);
                toast.setDuration(duration);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            }
        }


    }

    public static int getMainTid() {
        return mainTid;
    }
}
